package org.weso.desempleo.model;

import org.weso.desempleo.services.to.ListEdadesStatsTO;
import org.weso.desempleo.to.EdadStatsTO;

import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;

public class ChargerEdades extends Charger<ListEdadesStatsTO, EdadStatsTO> {
	
	public ChargerEdades() {
		if(months[0][0] == null) {
			initializeMonths();
		}
	}

	@Override
	public ListEdadesStatsTO obtain(String lang, String anyo, String month,
			String selector, String langAnt) {
		if(langAnt != null && !langAnt.equals("null") && !langAnt.equals(lang)) {
			month = getNewMonth(month, lang, langAnt);
		}
		String query = prepareSparqlQuery(anyo, selector, month, lang);
		QueryExecution qExec = initializeQuery("http://156.35.31.156/sparql", 
				query);
		ListEdadesStatsTO edades = (ListEdadesStatsTO)processResult(qExec.execSelect());
		return edades;
	}

	@Override
	public EdadStatsTO extractData(QuerySolution sol, int observaciones) {
		String label = "o" + String.valueOf(observaciones);
    	String aux = sol.get("month").toString();
    	String m = aux.substring(0, aux.indexOf('@'));
		String month = extractMonth(m);
    	int year = Integer.parseInt(sol.get("year").toString());
    	aux = sol.get("edad").toString();
    	String edad = aux.substring(0, aux.indexOf('@'));
    	String period = String.valueOf(year) + "-" + month;
    	String dataset = "Paro por edades en el principado de Asturias desde el año 2005";
    	int unemployment = Integer.parseInt(sol.get("value").toString());
    	EdadStatsTO age = new EdadStatsTO(edad, label, dataset, year, 
    			unemployment, period, month);
    	return age;
	}

	@Override
	public ListEdadesStatsTO processResult(ResultSet result) {
		ListEdadesStatsTO edades = new ListEdadesStatsTO();
    	int observaciones = 1;
		while(result.hasNext()) {
			EdadStatsTO genero = (EdadStatsTO)extractData(result.next(), 
					observaciones);
			edades.add(genero);
			observaciones++;
		}
    	return edades;
	}

	@Override
	public String prepareSparqlQuery(String anyo, String selector,
			String month, String lang) {
		String query="PREFIX o: <http://purl.org/observatory/observatory.owl#>\n"+
				"SELECT ?year ?month ?edad ?value\n FROM " + 
				"<http://purl.org/weso/testObservatory/observatoryByAges/> \n WHERE{ ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> " +
							"<http://purl.org/linked-data/cube#Observation>; o:refYear ?year; o:refMonth ?month; o:unemployment ?value; o:refAges ?edad"; 
		query += parseYear(anyo);
		query += " FILTER (langMatches(lang(?month), '" + lang +"')" + parseMonth(month) + ")\n";
		query += " FILTER (langMatches(lang(?edad), '" + lang +"')" + parseEdad(selector, lang) + ")";
		return query+"}";
	}
	
	/**
	 * This method parse the variable 'edad' to obtain a part of the SPARL 
	 * query.
	 * @param edad The value of ages that the user has selected in the form.
	 * @param lang language selected by the user
	 * @return A part of the SPARQL query.
	 */
	private String parseEdad(String edad, String lang) {
		if(edad.equals("Todos") || edad.equals("All"))
			return "";
		return "&& str(?edad)=\"" + prepareEdad(edad, lang) +"\"";
	}
	
	/**
	 * This method obtain the RDF value of ages that the user has selected in
	 * the form.
	 * @param edad The value of ages that the user has selected.
	 * @param lang language selected by the user
	 * @return A string with RDF value of ages.
	 */
	private String prepareEdad(String edad, String lang) {
		if(edad.equals("<25"))
			return lang.equals("es")?"menor25":"less25";
		else if(edad.equals(">=25<45"))
			return lang.equals("es")?"entre2545":"between2545";
		else
			return lang.equals("es")?"mayor45":"older45";
	}

}
